import Vue from 'vue'
import MinRequest from '@/utils/MinRequest'
import globalConfig from '@/config'


const minRequest = new MinRequest()

const HttpErrorCode = {
	400: '请求错误',
	401: '未授权，请登陆',
	403: '拒绝访问',
	404: '请求地址出错',
	408: '请求超时',
	500: '服务器内部错误',
	501: '服务未实现',
	502: '网关错误',
	503: '服务不可用',
	504: '网关超时',
	505: 'HTTP版本不受支持'
}
// 请求拦截器
minRequest.interceptors.request((request) => {
	
	//請求前,增加token參數
	request.header["Authorization"] = uni.getStorageSync("token");
	return request;
})

// 响应拦截器
minRequest.interceptors.response((response) => {
	if (response.statusCode == 403) {
		if (response.data.indexOf('300')) {
			//認證過期
			uni.showToast({
				icon: "none",
				position: "center",
				title: "登錄過期,請重新登錄",
				success: () => {
					setTimeout(function() {
						uni.reLaunch({
							url: "/pages/login/login"
						})
					}, 1500)
				}
			})
		} else if (response.data.indexOf('400')) {
			//非法token
			uni.showToast({
				icon: "none",
				position: "center",
				title: "非法認證請求",
				success: () => {
					setTimeout(function() {
						uni.reLaunch({
							url: "/pages/login/login"
						})
					}, 1500)
				}
			})
		} else if (response.data.indexOf('500')) {
			//認證Token未知異常
			uni.showToast({
				icon: "none",
				position: "center",
				title: "未知認證異常,重新登錄",
				success: () => {
					setTimeout(function() {
						uni.reLaunch({
							url: "/pages/login/login"
						})
					}, 1500)
				}
			})
		} else if (response.data.indexOf('600')) {
			//Token為空
			uni.showToast({
				icon: "none",
				position: "center",
				title: "未登錄,請登錄",
				success: () => {
					setTimeout(function() {
						uni.reLaunch({
							url: "/pages/login/login"
						})
					}, 1500)
				}
			})
		}
		return false;
	}
	else if(response.statusCode==200){
		if(response.data.IsSuccess){
			return response.data.Data;
		}else{
			uni.showModal({
				content: response.data.ErrorMessage,
				showCancel: false
			});
			return;
		}
	}else{
		uni.showModal({
			content: HttpErrorCode[response.statusCode],
			showCancel: false
		});
	}
})

// 设置默认配置
minRequest.setConfig((config) => {
	config.baseURL = globalConfig.baseUrl
	return config
})

export default {
	// 这里统一管理api请求
	apis: {
		login(params) {
			return minRequest.post('/UserInfo/Login', params)
		},
		userPwdModify(params) {
			return minRequest.post('/post/user/pwd/modify', params)
		}		 
	}
}
